# 清理本地分支，只保留dev分支
# 使用说明：
# 将/path/to/your/repo替换为您实际的Git仓库路径。
# 运行此脚本前，请确保您有权限对指定的仓库及其子模块进行修改。
# 脚本中使用了git checkout和git branch -D命令，这两个命令会直接修改您的仓库状态，请谨慎使用。
# 如果您希望保留某些特定的分支，可以在delete_local_branches函数中添加额外的检查逻辑。

import subprocess
import os

def run_command(command, cwd=None):
    """运行shell命令并返回输出"""
    result = subprocess.run(command, shell=True, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd)
    return result.stdout.decode('utf-8').strip()

def get_submodules(repo_path):
    """获取给定仓库的所有子模块路径"""
    command = 'git submodule status'
    output = run_command(command, cwd=repo_path)
    submodules = [line.split()[1] for line in output.splitlines()]
    return submodules

def switch_to_dev_branch(repo_path):
    """切换到dev分支"""
    command = 'git checkout dev'
    try:
        run_command(command, cwd=repo_path)
        print(f"成功切换 {repo_path} 到 dev 分支")
    except subprocess.CalledProcessError as e:
        print(f"切换 {repo_path} 到 dev 分支失败: {e.stderr}")

def delete_local_branches(repo_path):
    """删除除了dev以外的所有本地分支"""
    # 获取所有本地分支
    command = 'git branch --format="%(refname:short)"'
    branches = run_command(command, cwd=repo_path).split()
    
    # 删除除dev外的所有分支
    for branch in branches:
        if branch != 'dev':
            delete_command = f'git branch -D {branch}'
            try:
                run_command(delete_command, cwd=repo_path)
                print(f"已删除 {repo_path} 中的分支 {branch}")
            except subprocess.CalledProcessError as e:
                print(f"删除 {repo_path} 中的分支 {branch} 失败: {e.stderr}")

def main():
    repo_path = '/home/wxc/SGSim'  # 替换为您的仓库路径
    submodules = get_submodules(repo_path)
    
    # 首先处理主仓库
    switch_to_dev_branch(repo_path)
    delete_local_branches(repo_path)
    
    # 然后处理每个子模块
    for submodule in submodules:
        submodule_path = os.path.join(repo_path, submodule)
        switch_to_dev_branch(submodule_path)
        delete_local_branches(submodule_path)

if __name__ == "__main__":
    main()